package com.yixun.qfbao.hander;

import com.yixun.qfbao.api.service.PremisesRecommenderService;
import com.yixun.qfbao.apidto.BatchAddPremisesRecommenderReqDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.vo.BatchAddPremisesRecommenderReqVo;
import com.yixun.qfbao.xf.model.PremisesRecommender;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.PremisesStatusEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: channel-parent
 *
 * @description: 同步设置推荐人到其他楼盘
 *
 * @author: Seven.wang
 *
 * @create: 2019-11-06 13:38
 **/
@Service("batchAddPremisesRecommender")
public class BatchAddPremisesRecommenderHander extends CommonAbstractHander {

    private static Logger logger= LoggerFactory.getLogger(BatchAddPremisesRecommenderHander.class);

    @Autowired
    PremisesRecommenderService premisesRecommenderService;
    @Autowired
    PremisesService premisesService;

    @Override
    public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
        BatchAddPremisesRecommenderReqVo req = (BatchAddPremisesRecommenderReqVo)reqDto;
        BatchAddPremisesRecommenderReqDto dto = req.getParams();
        BaseResponseDTO<String> resDto = new BaseResponseDTO<>();
        try {
            List<PremisesRecommender> prList = buildPremisesRecommenderList(dto);
            if(CollectionUtils.isEmpty(prList)){
                resDto.setResult(ResultEnum.FAIL.getNo());
                resDto.setErrorMsg("新增失败，无新增的推荐人！");
                return resDto;
            }
            premisesRecommenderService.batchAdd(prList);

            // 批量修改楼盘状态为待审核
            List<Long> premisesIds = dto.getPremisesIds();
            if(CollectionUtils.isNotEmpty(premisesIds)){
                premisesIds.forEach(item -> {
                    // 推荐人变更,楼盘待审核
                    PremisesDto premisesDto = new PremisesDto();
                    premisesDto.setId(item);
                    premisesDto.setPremisesStatus(PremisesStatusEnum.type0.getNo());
                    premisesService.update(premisesDto);
                });
            }

            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setResData("同步成功");
        } catch (Exception e) {
            logger.error("handler batch add PremisesRecommender error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setErrorMsg("批量插入推荐人失败！");
        }
        return resDto;
    }

    /**
     *  构建同步设置楼盘的推荐人列表
     * @param dto
     * @return
     */
    private List<PremisesRecommender> buildPremisesRecommenderList(BatchAddPremisesRecommenderReqDto dto){
        // 构建楼盘的现有推荐人集合
        HashMap<Long, HashMap<Long, PremisesRecommender>> rootMap = new HashMap<>();
        // 获取楼盘已存在的推荐人列表
        List<PremisesRecommender> existList = premisesRecommenderService.selectListByIds(dto.getPremisesIds(),dto.getRecommenderIds(),"0");
        if(CollectionUtils.isNotEmpty(existList)){
            // 将以存在的推荐人列表保存至Map中
            HashMap<Long, Long> idMap = new HashMap<>();
            for(PremisesRecommender p : existList){
                if(rootMap.isEmpty()){
                    HashMap<Long, PremisesRecommender> secondMap = new HashMap<>();
                    secondMap.put(p.getRecommenderId(),p);
                    rootMap.put(p.getPremisesId(), secondMap);
                }else{
                    HashMap<Long, PremisesRecommender> secondMap = rootMap.get(p.getPremisesId());
                    if(secondMap == null){
                        secondMap = new HashMap<>();
                        secondMap.put(p.getRecommenderId(),p);
                    }else{
                        if(secondMap.get(p.getRecommenderId()) == null){
                            secondMap.put(p.getRecommenderId(),p);
                        }
                    }
                    rootMap.put(p.getPremisesId(), secondMap);
                }
            }
        }
        // 遍历需保存的楼盘和推荐人集合
        List<PremisesRecommender> prList = new ArrayList<>();
        for(Long pid : dto.getPremisesIds()){
            for(Long rid : dto.getRecommenderIds()){
                // 如果需添加的推荐人，在现有楼盘的推荐人列表中已存在，则不重复添加
                if(!rootMap.isEmpty() && rootMap.get(pid) != null && rootMap.get(pid).get(rid) != null){
                    continue;
                }
                PremisesRecommender pr = new PremisesRecommender();
                pr.setPremisesId(pid);
                pr.setRecommenderId(rid);
                pr.setRecommenderUuid(UUID.randomUUID().toString().replace("-", ""));
                pr.setCreateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
                pr.setUpdateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
                pr.setCreateTime(new Date());
                pr.setUpdateTime(new Date());
                pr.setDelFlag("0");
                prList.add(pr);
            }
        }
        return prList;
    }
}
